package com.zzj.service.impl;

import com.zzj.entity.File;
import com.zzj.mapper.FileMapper;
import com.zzj.service.IFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzj.utils.Utils;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 文件地址表 服务实现类
 * </p>
 *
 * @author zzj
 * @since 2022-12-08
 */
@Service
@Log4j2
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService {

  private Utils utils = new Utils();

  @Override
  public String addOne(MultipartFile file, String filePath) throws IOException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    java.io.File folder = new java.io.File(filePath + simpleDateFormat.format(new Date()));
    if (!folder.exists()) {
      if (folder.mkdirs()) {
        log.info("文件夹" + folder.getAbsolutePath() + "已创建");
      } else {
        log.error("文件夹创建失败");
      }
    }
    file = utils.rename(file);
    String fileName = file.getName();
    java.io.File dest = new java.io.File(folder, fileName);
    file.transferTo(dest);
    return "/upload/" + simpleDateFormat.format(new Date()) + "/" + fileName;
  }
}
